import { createStore } from 'vuex'
import request from '../utils/request'

export default createStore({
    state: {
        token: localStorage.getItem('token') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        SET_USERINFO(state, userInfo) {
            state.userInfo = userInfo
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
        },
        CLEAR_USER(state) {
            state.token = ''
            state.userInfo = {}
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        }
    },
    actions: {
        // 登录
        async login({ commit }, userInfo) {
            try {
                const response = await request({
                    url: '/login',
                    method: 'POST',
                    data: userInfo
                })
                if (response.data) {
                    commit('SET_TOKEN', response.data.token)
                    commit('SET_USERINFO', response.data.userInfo)
                }
                return response
            } catch (error) {
                console.error('登录失败:', error)
                throw error
            }
        },
        // 登出
        logout({ commit }) {
            commit('CLEAR_USER')
            return Promise.resolve()
        }
    }
}) 